package com.fengze.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fengze.business.domain.*;
import com.fengze.business.mapper.*;
import com.fengze.business.vo.ClientLibraryVO;
import com.fengze.common.annotation.AutoSetInsertValue;
import com.fengze.common.annotation.AutoSetUpdateValue;
import com.fengze.common.core.domain.entity.SysUser;
import com.fengze.common.utils.DateUtils;
import com.fengze.common.utils.StringUtils;
import com.fengze.system.mapper.SysUserMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fengze.business.service.IProjectInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 立项登记Service业务层处理
 *
 * @author lug
 * @date 2024-02-02
 */
@Service
public class ProjectInfoServiceImpl implements IProjectInfoService
{
    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private ProjectPlanMapper projectPlanMapper;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ClientLibraryMapper clientLibraryMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private ReceivePaymentMapper receivePaymentMapper;

    /**
     * 查询立项登记
     *
     * @param id 立项登记主键
     * @return 立项登记
     */
    @Override
    public ProjectInfo selectProjectInfoById(Long id)
    {
        ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoById(id);
        List<ProjectPlan> planList = projectPlanMapper.selectByProjectId(id);
        projectInfo.setPlanList(planList);
        return projectInfo;
    }

    /**
     * 查询立项登记列表
     *
     * @param projectInfo 立项登记
     * @return 立项登记
     */
    @Override
    public List<ProjectInfo> selectProjectInfoList(ProjectInfo projectInfo)
    {
        List<ProjectInfo> projectInfos = projectInfoMapper.selectProjectInfoList(projectInfo);
        for (int i = 0; i < projectInfos.size(); i++) {
            ProjectInfo info = projectInfos.get(i);
            // 查询创建人信息
            Long userId = info.getUserId();
            SysUser sysUser = userMapper.selectUserById(userId);
            info.setCreateUserName(sysUser.getNickName());
            // 查询客户名称
            Long clientId = info.getClientId();
            ClientLibraryVO libraryVO = clientLibraryMapper.selectVOById(clientId);
            info.setClientName(libraryVO.getName());
            // 查询付款金额
            Payment payment = new Payment();
            payment.setProjectId(info.getId());
            payment.setPaymentStatus(2);
            List<Payment> payments = paymentMapper.selectPaymentList(payment);
            BigDecimal paymentTotal = payments.stream().filter(o -> ObjectUtils.isNotEmpty(o.getPaymentMoney()))
                    .map(Payment::getPaymentMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            info.setPaymentTotal(paymentTotal);
            // 查询收款金额
            ReceivePayment receivePayment = new ReceivePayment();
            receivePayment.setProjectId(info.getId());
            List<ReceivePayment> receivePayments = receivePaymentMapper.selectReceivePaymentList(receivePayment);
            BigDecimal receiveTotal = receivePayments.stream().filter(o -> ObjectUtils.isNotEmpty(o.getReceiveMoney()))
                    .map(ReceivePayment::getReceiveMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            info.setReceiveTotal(receiveTotal);
        }
        return projectInfos;
    }

    /**
     * 新增立项登记
     *
     * @param projectInfo 立项登记
     * @return 结果
     */

    @Transactional(rollbackFor = Exception.class)
    @AutoSetInsertValue
    @Override
    public int insertProjectInfo(ProjectInfo projectInfo)
    {
        projectInfo.setCreateTime(DateUtils.getNowDate());
        int insertCount = projectInfoMapper.insertProjectInfo(projectInfo);
        String jsonArrStr = projectInfo.getPlanStr();
        if (StringUtils.isNotEmpty(jsonArrStr)) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, ProjectPlan.class);
                List<ProjectPlan> planList = mapper.readValue(jsonArrStr,listType);
                if (CollectionUtils.isNotEmpty(planList)) {
                    Long userId = projectInfo.getUserId();
                    Long deptId = projectInfo.getDeptId();
                    for (ProjectPlan projectPlan : planList) {
                        projectPlan.setUserId(userId);
                        projectPlan.setDeptId(deptId);
                        projectPlan.setProjectId(projectInfo.getId());
                    }
                    projectPlanMapper.insertBatch(planList);
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        return insertCount;
    }

    /**
     * 修改立项登记
     *
     * @param projectInfo 立项登记
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @AutoSetUpdateValue
    @Override
    public int updateProjectInfo(ProjectInfo projectInfo)
    {
        projectInfo.setUpdateTime(DateUtils.getNowDate());
        return projectInfoMapper.updateProjectInfo(projectInfo);
    }

    /**
     * 批量删除立项登记
     *
     * @param ids 需要删除的立项登记主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteProjectInfoByIds(Long[] ids)
    {
        projectPlanMapper.deleteByProjectIds(ids);
        return projectInfoMapper.deleteProjectInfoByIds(ids);
    }

    /**
     * 删除立项登记信息
     *
     * @param id 立项登记主键
     * @return 结果
     */
    @Override
    public int deleteProjectInfoById(Long id)
    {
        return projectInfoMapper.deleteProjectInfoById(id);
    }
}
